package cn.iocoder.yudao.module.dine.print.controller.app;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.iocoder.yudao.framework.thirdparty.feieyun.FeiSDK;
import cn.iocoder.yudao.module.dine.print.service.core.CoreDinePrintRecordService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import static cn.iocoder.yudao.module.api.dine.ConfigConstants.PRINT_ORDER_SN_MOCK_PREFIX;

/**
 * <pre>
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * 前端控制器
 * OOoO0OOoO0OOOooo0oOOOO0OOOOO0oooOO0ooOOO0Ooooo0OOOOo0ooooO0OOooo0Ooooo0OOOOO
 * </pre>
 *
 * @author 山野羡民（1032694760@qq.com）
 * @since 2025/08/22
 */
@Tag(name = "用户 APP - 小票打印机")
@RestController
@RequestMapping("/dine/printer")
@Slf4j
public class AppDinePrintNotifyController {
    @Resource
    private CoreDinePrintRecordService coreDinePrintRecordService;

    @RequestMapping(value = "/notify", method = {RequestMethod.POST, RequestMethod.GET})
    @Operation(summary = "打印回调")
    @PermitAll
    public String notify(@RequestParam Map<String, String> query) {
        // 飞鹅打印回调接口文档：https://help.feieyun.com/home/doc/zh;nav=1-7
        // 实测回调数据：orderId=332107118_20250829162029_290586210&sign=jCrpTKnqVnW9GW5fyh%2FwWnQGYKNj4rLVjUOcwxBvD6XREACL8R9h5pa6TqdxSClUcbtctETyOqxbRjrDcAAP1NHb8%2BpKee0xc6fEIzWrudt%2B2SKUmveR0XHnE9LbO1PGHak%2FShYdHvLQQEf0Xa7iRVWHlk1wYwH%2F%2BkKH3vtHFiZjms%2B%2Fxlk5GLks4%2FkYYIpjJIuXCWad42vWHY2%2FPOYlb%2BuholxrKvwFsHKJ1nDzUDh%2FiBVm0yKl0KahB2OuuyXQGq1aYEf9TPXvS3UY5GvjhvCB%2FXadgzL66g%2BuAmKq2d%2BPLYVMBhx7fcYfQ9ikWRTT8nMFSAvbnnp8WqJ%2B%2BRnlzw%3D%3D&stime=1756456967&status=1
        String orderId = query == null ? null : query.get("orderId");
        if (StrUtil.isBlank(orderId)) {
            log.warn("飞鹅云打印回调数据无效：打印单编号缺失");
        } else {
            String notifyData = JSONUtil.toJsonStr(query);
            try {
                Boolean state;
                if (StrUtil.startWith(orderId, PRINT_ORDER_SN_MOCK_PREFIX)) {
                    state = true;
                } else {
                    state = FeiSDK.queryOrderState(orderId);
                }
                coreDinePrintRecordService.update(orderId, Boolean.TRUE.equals(state), notifyData);
            } catch (Exception e) {
                coreDinePrintRecordService.update(orderId, false, notifyData);
            }
        }
        // 注：开发者接收后需立即返回SUCCESS，如5秒内不返回或返回数据格式错误，平台会重新推送（实测会重新推送2次）。
        return "SUCCESS";
    }

}
